package com.ruoyi.flow.common.tools.mediaconverter.converter.command;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 该类用于监视Process的执行，解决{@code Process.waitFor()}造成的阻塞。
 * <br/>
 * 我们在调用Process的waitFor方法时经常会遇到明明Process已经结束了，但是waitFor还处于阻塞，那是因为Process的inputStream缓存造成的。
 * <br/>
 * 通过启动该线程，实时清空缓存就可以解决该问题。
 */
public class CommandWatcher extends Thread {
    private Process process;
    boolean over;
    ArrayList<String> stream;

    public CommandWatcher(Process process) {
        this.process = process;
        this.over = false;
        this.stream = new ArrayList<>();
    }

    @Override
    public void run() {
        if(process == null){
            return;
        }
        Scanner br = null;
        try {
            br = new Scanner(process.getInputStream());
            while (true){
                if(process == null || over){
                    break;
                }
                while (br.hasNextLine()){
                    String tempStream = br.nextLine();
                    if(StringUtils.isEmpty(StringUtils.trim(tempStream))){
                        continue;
                    }
                    stream.add(tempStream);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(br);
        }
    }

    public void setOver(boolean over) {
        this.over = over;
    }

    public ArrayList<String> getStream() {
        return stream;
    }
}
